<template>
  <d-dialog
    ref="dialog"
    :header="formData.isEdit ? '编辑账号' : '新增账号'"
    api="system/user"
    v-model:data="formData"
    v-model:visible="visible"
    :rules="rules"
  >
    <t-form-item label="姓名" name="nickName">
      <t-input v-model="formData.nickName" placeholder="请输入姓名"></t-input>
    </t-form-item>
    <t-form-item label="账号" name="userName">
      <t-input v-model="formData.userName" placeholder="请输入账号"></t-input>
    </t-form-item>
    <t-form-item label="邮箱" name="email">
      <t-input v-model="formData.email" placeholder="请输入邮箱"></t-input>
    </t-form-item>
    <t-form-item label="手机号" name="phonenumber">
      <t-input v-model="formData.phonenumber" placeholder="请输入手机号"></t-input>
    </t-form-item>
    <t-form-item label="所属部门" name="deptId">
      <t-tree-select v-model="formData.deptId" :data="system.deptList" />
    </t-form-item>
    <t-form-item label="角色" name="roleIds">
      <t-select
        v-model="formData.roleIds"
        :options="system.rolesList"
        placeholder="请选择角色"
        multiple
      />
    </t-form-item>
    <t-form-item label="关联站群" name="websiteGroupId">
      <t-select
        v-model="formData.websiteGroupId"
        :options="member.websiteGroupList"
        placeholder="请选择角色"
      />
    </t-form-item>
    <t-form-item label="状态" name="status">
      <t-radio-group v-model="formData.status" :options="statusList" />
    </t-form-item>
  </d-dialog>
</template>

<script setup>
import { useSystem } from '@/store/system'
import { useDict } from '@/store/dict'
import { useMember } from '@/store/member'
import { merge } from '@common'
import { get } from '@common'
import { ref, computed } from 'vue'
const INIT_STATUS = {
  nickName: '',
  userName: '',
  password: '',
  email: '',
  userId: '',
  status: '0',
  deptId: undefined,
  roleIds: [],
  websiteGroupId: ''
}
const dialog = ref(null)
const visible = ref(false)
const formData = ref({ ...INIT_STATUS })
const websiteGroupList = ref([])
const rules = {
  nickName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  userName: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  roleIds: [{ required: true, message: '请选择角色', trigger: 'blur' }],
  email: [{ required: true, message: '请输入邮箱地址', trigger: 'blur' }]
}
const system = useSystem()
const dict = useDict()
const member = useMember()
const statusList = computed(() => {
  return dict.dict_enable_list
})

const show = async (info = {}) => {
  const isEdit = !!info.userId
  if (isEdit) {
    const res = await get(`system/user/${info.userId}`)
    info.roleIds = (res.data || []).roles.map((e) => {
      return e.roleId
    })
  }
  const obj = merge({ ...INIT_STATUS, isEdit }, info)
  formData.value = obj
  visible.value = true
}
member.getWebsiteGroupList()
system.getRolesListAll()
system.getDeptListAll()
defineExpose({ show })
</script>
